package edu.sdbi.judge.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Component
public class HttpUtil {

    @Resource
    private RestTemplate restTemplate;
    @Value("${api.base.url:http://localhost:8080/}") // 从配置文件读取基础URL
    private String baseUrl;


    private String sessionId;

    /**
     * 发送 GET 请求
     *
     * @param url     请求地址
     * @param headers 请求头（可为 null）
     * @param params  查询参数（可为 null）
     * @return 响应体字符串
     */
    public String doGet(String url, Map<String, String> headers, Map<String, String> params) {
        // 构建完整的URL
        String fullUrl = buildFullUrl(url);
        // 拼接参数
        if (params != null && !params.isEmpty()) {
            StringBuilder sb = new StringBuilder("?");
            params.forEach((k, v) -> sb.append(k).append("=").append(v).append("&"));
            fullUrl += sb.substring(0, sb.length() - 1);
        }

        HttpHeaders httpHeaders = new HttpHeaders();
        if (headers != null) headers.forEach(httpHeaders::set);

        if (sessionId != null) {
            // 添加 Cookie 到请求头
            httpHeaders.add("Cookie", "JSESSIONID=" + sessionId);
        }

        HttpEntity<String> entity = new HttpEntity<>(httpHeaders);
        ResponseEntity<String> response = restTemplate.exchange(fullUrl, HttpMethod.GET, entity, String.class);
        return response.getBody();
    }

    /**
     * 发送 POST 请求（application/json）
     *
     * @param url     请求地址
     * @param headers 请求头（可为 null）
     * @param body    请求体（Java对象或 Map）
     * @return 响应体字符串
     */
    public String doPost(String url, Map<String, String> headers, Object body) {
        // 构建完整的URL
        String fullUrl = buildFullUrl(url);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        if (headers != null) headers.forEach(httpHeaders::set);

        if (sessionId != null) {
            // 添加 Cookie 到请求头
            httpHeaders.add("Cookie", "JSESSIONID=" + sessionId);
        }

        HttpEntity<Object> entity = new HttpEntity<>(body, httpHeaders);
        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
        return response.getBody();
    }

    /**
     * 发送 POST 请求（application/）
     *
     * @param url      请求地址
     * @param headers  请求头（可为 null）
     * @param valueMap 请求表单
     * @return 响应体字符串
     */
    public String doPostFormData(String url, Map<String, String> headers, MultiValueMap<String, Object> valueMap) {
        // 构建完整的URL
        String fullUrl = buildFullUrl(url);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
        if (headers != null) headers.forEach(httpHeaders::set);

        if (sessionId != null) {
            // 添加 Cookie 到请求头
            httpHeaders.add("Cookie", "JSESSIONID=" + sessionId);
        }
        // 获取存储sessionId
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(valueMap, httpHeaders);
        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
        HttpHeaders responseHeaders = response.getHeaders();
        List<String> cookies = responseHeaders.get("Set-Cookie");
        if (cookies != null) {
            for (String cookie : cookies) {
                if (cookie.toLowerCase().contains("sessionid")) {
                    sessionId = cookie.split(";")[0].split("=")[1];
                }
            }
        }

        return response.getBody();
    }

    /**
     * 构建完整的绝对URL
     */
    private String buildFullUrl(String url) {
        // 如果已经是绝对路径，则直接返回
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            url = "http://" + url;
        }
//        if (!url.endsWith("/")) {
//            url = url + "/";
//        }
        return url;
    }
}






